/*!
 @header      CarouselView.m
 @discussion  广告轮播图
 @author      Created by liux on 16/8/19
 @copyright   Copyright © 2016年 eeepay. All rights reserved.
 */

#import "CarouselView.h"
#import "SCBannerModel.h"
@interface CarouselView () <UIScrollViewDelegate>
@property (strong, nonatomic) UIScrollView *scrollView;
@property (strong, nonatomic) UIImageView * leftView;
@property (strong, nonatomic) UIImageView * middleView;
@property (strong, nonatomic) UIImageView * rightView;
@property (strong, nonatomic) NSMutableArray * dataArr;
@property (strong, nonatomic) NSTimer * timer;
@property (strong, nonatomic) UIPageControl * pageCtl;
@property (strong, nonatomic) UITapGestureRecognizer * tap;
@property (assign, nonatomic) NSInteger currentPage;
@property (assign, nonatomic) BOOL isDragging;
@property (assign, nonatomic) BOOL isFristIn;
@property (nonatomic, strong) UILabel *showProgressLabel;
@end

@implementation CarouselView
- (instancetype)initWithFrame:(CGRect)frame data:(NSArray *)data delegate:(id<CarouselViewDelegate>)delegate
{
    self = [super initWithFrame:frame];
    if (self) {
        _dataArr = [NSMutableArray array];
        for (int i=0;i<data.count;i++) {
            SCBannerModel *model = data[i];
            [_dataArr addObject:model.pic?model.pic:@""];
        }
        _delegate = delegate;
        //        NSLog(@"--------%ld",(unsigned long)_dataArr.count);
        _currentPage = 0;
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];
        _scrollView.delegate = self;
        _scrollView.contentSize = CGSizeMake(self.bounds.size.width * 3, self.bounds.size.height);
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.pagingEnabled = YES;
        _scrollView.backgroundColor = [UIColor clearColor];
        _scrollView.delegate = self;
        _scrollView.contentOffset = CGPointMake(self.bounds.size.width, 0);
        [self addSubview:_scrollView];
        
        _leftView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];
        _middleView = [[UIImageView alloc] initWithFrame:CGRectMake(self.bounds.size.width, 0, self.bounds.size.width, self.bounds.size.height)];
        _rightView = [[UIImageView alloc] initWithFrame:CGRectMake(self.bounds.size.width*2, 0, self.bounds.size.width, self.bounds.size.height)];
        _middleView.contentMode = UIViewContentModeScaleToFill;
        _leftView.contentMode   = UIViewContentModeScaleToFill;
        _rightView.contentMode  = UIViewContentModeScaleToFill;
        [_scrollView addSubview:_leftView];
        [_scrollView addSubview:_middleView];
        [_scrollView addSubview:_rightView];
        
        _pageCtl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, self.bounds.size.height - 30, self.bounds.size.width, 30)];
        _pageCtl.userInteractionEnabled = NO;
        _pageCtl.currentPageIndicatorTintColor = [UIColor lightGrayColor];
        _pageCtl.pageIndicatorTintColor = [UIColor whiteColor];
        _pageCtl.numberOfPages = _dataArr.count;
//        [self addSubview:_pageCtl];
        
        
        _showProgressLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.bounds.size.width - 80, self.bounds.size.height - 40, 60, 40)];
        _showProgressLabel.textColor = [UIColor whiteColor];
        _showProgressLabel.textAlignment = NSTextAlignmentRight;
        _showProgressLabel.text = [NSString stringWithFormat:@"1/%ld",_dataArr.count];
        [self addSubview:_showProgressLabel];
        //设置单击手势
        _tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myTap:)];
        _tap.numberOfTapsRequired = 1;
        _tap.numberOfTouchesRequired = 1;
        [_scrollView addGestureRecognizer:_tap];
        if (_dataArr.count == 1) {
             [_middleView yy_setImageWithURL:[NSURL URLWithString:[_dataArr objectAtIndex:_currentPage]] placeholder:[UIImage imageNamed:@""]];
            _scrollView.scrollEnabled = NO;
        } else {
            if (!_timer) {
                _timer = [NSTimer scheduledTimerWithTimeInterval:2.5 target:self selector:@selector(imageCarousel) userInfo:nil repeats:YES];
            }
            [self reloadData];
        }
    }
    return self;
}

#pragma mark - 单击手势
- (void)myTap:(UITapGestureRecognizer *)sender
{
    if ([self.delegate respondsToSelector:@selector(didClickPageAtIndex:)]) {
        [self.delegate didClickPageAtIndex:_currentPage];
    }
}

- (void)reloadData
{
    if (_currentPage == 0) {
        [_leftView yy_setImageWithURL:[NSURL URLWithString:[_dataArr lastObject]] placeholder:[UIImage imageNamed:@""]];
        [_middleView yy_setImageWithURL:[NSURL URLWithString:[_dataArr objectAtIndex:_currentPage]] placeholder:[UIImage imageNamed:@""]];
        [_rightView yy_setImageWithURL:[NSURL URLWithString:[_dataArr objectAtIndex:_currentPage+1]] placeholder:[UIImage imageNamed:@""]];
    } else if (_currentPage == _dataArr.count-1) {
        [_leftView yy_setImageWithURL:[NSURL URLWithString:[_dataArr objectAtIndex:_currentPage-1]] placeholder:[UIImage imageNamed:@""]];
        [_middleView yy_setImageWithURL:[NSURL URLWithString:[_dataArr objectAtIndex:_currentPage]] placeholder:[UIImage imageNamed:@""]];
        [_rightView yy_setImageWithURL:[NSURL URLWithString:[_dataArr firstObject]] placeholder:[UIImage imageNamed:@""]];
    } else {
        [_leftView yy_setImageWithURL:[NSURL URLWithString:[_dataArr objectAtIndex:_currentPage-1]] placeholder:[UIImage imageNamed:@""]];
        [_middleView yy_setImageWithURL:[NSURL URLWithString:[_dataArr objectAtIndex:_currentPage]] placeholder:[UIImage imageNamed:@""]];
        [_rightView yy_setImageWithURL:[NSURL URLWithString:[_dataArr objectAtIndex:_currentPage+1]] placeholder:[UIImage imageNamed:@""]];
    }

    //设置当前的分页
    _pageCtl.currentPage = _currentPage;
    _showProgressLabel.text = [NSString stringWithFormat:@"%ld/%ld",_currentPage + 1,_dataArr.count];
    //显示中间页
    if (_isFristIn) {
        if (!_isDragging) {
            _scrollView.contentOffset = CGPointMake(0, 0);
            [UIView animateWithDuration:0.5 animations:^{
                self->_scrollView.contentOffset = CGPointMake(self.bounds.size.width, 0);
            } completion:^(BOOL finished) {
            }];
        } else {
            _scrollView.contentOffset = CGPointMake(self.bounds.size.width, 0);
            _isDragging = NO;
        }
    }
    _isFristIn = YES;
}

#pragma mark scrollvie停止滑动
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //手动滑动时候暂停自动替换
    if ([_timer isValid]) {
        [_timer invalidate];
        _timer = nil;
    }
    _timer = [NSTimer scheduledTimerWithTimeInterval:2.5 target:self selector:@selector(imageCarousel) userInfo:nil repeats:YES];
    //往前翻
    if (_scrollView.contentOffset.x/self.bounds.size.width <= 0) {
        if (_currentPage-1 < 0) {
            _currentPage = _dataArr.count-1;
        } else {
            _currentPage --;
        }
    }
    //往后翻
    if (_scrollView.contentOffset.x /self.bounds.size.width >= 2) {
        if (_currentPage == _dataArr.count-1) {
            _currentPage = 0;
        } else {
            _currentPage ++;
        }
    }
    _isDragging = YES;
    [self reloadData];
}

#pragma mark - 图片轮播
- (void)imageCarousel
{
    if (_currentPage == _dataArr.count-1) {
        _currentPage = 0;
    } else {
        _currentPage ++;
    }
    [self reloadData];
}


@end
